<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus"
import type { AddForm, CardItem, Page, SearchForm } from "./apis/type"
import { ElMessage, ElMessageBox } from "element-plus"

import { reactive, ref } from "vue"
import {
  createCardDataApi,
  deleteCardDataApi,
  getMonthCardDataApi,
  getMonthCardDetailDataApi,
  renewCardDataApi,
  updateCardDataApi
} from "./apis/monthCard.ts"

/* 搜索表单 */
const searchForm = reactive<SearchForm>({
  carNumber: "",
  personName: "",
  cardStatus: ""
})

/* 状态下拉 */
const statusOpts = reactive([
  { label: "正常", value: 1 },
  { label: "即将过期", value: 2 },
  { label: "已过期", value: 0 }
])

/* 表格 & 分页 */
const tableData = ref<CardItem[]>([])
const page = reactive<Page>({ page: 1, pageSize: 10, total: 0 })
const selectedRows = ref<CardItem[]>([])

/* 添加/编辑弹窗 */
const dialog = reactive({
  visible: false,
  title: "添加月卡"
})
const addFormRef = ref<FormInstance>()
const isEdit = ref(false)
const addForm = reactive<AddForm>({
  personName: "",
  phoneNumber: "",
  carNumber: "",
  carBrand: "",
  cardStartDate: "",
  cardEndDate: "",
  paymentAmount: "",
  paymentMethod: "Alipay"
})
const rules = reactive<FormRules<AddForm>>({
  personName: [{ required: true, message: "请输入车主姓名", trigger: "blur" }],
  phoneNumber: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "手机号格式错误", trigger: "blur" }
  ],
  carNumber: [{ required: true, message: "请输入车牌号码", trigger: "blur" }],
  carBrand: [{ required: true, message: "请输入车辆品牌", trigger: "blur" }],
  cardStartDate: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  cardEndDate: [{ required: true, message: "请选择结束时间", trigger: "change" }],
  paymentAmount: [{ required: true, message: "请输入支付金额", trigger: "blur" }],
  paymentMethod: [{ required: true, message: "请选择支付方式", trigger: "change" }]
})

/* 搜索数据 */
async function handleSearch() {
  const { data } = await getMonthCardDataApi({ ...searchForm, ...page })
  tableData.value = data.rows
  page.total = data.total
}

/* 添加弹窗 */
function handleAdd() {
  isEdit.value = false
  dialog.title = "添加月卡"
  Object.assign(addForm, {
    personName: "",
    phoneNumber: "",
    carNumber: "",
    carBrand: "",
    cardStartDate: "",
    cardEndDate: "",
    paymentAmount: "",
    paymentMethod: "Alipay"
  })
  dialog.visible = true
}

/* 编辑弹窗 */
async function handleEdit(row: CardItem) {
  isEdit.value = true
  dialog.title = "编辑月卡"
  const { data } = await getMonthCardDetailDataApi(row.id)
  Object.assign(addForm, data)
  if (data.rechargeList && Array.isArray(data.rechargeList)) {
    addForm.rechargeId = data.rechargeList[0]?.rechargeId
  }
  dialog.visible = true
}

/* 提交添加/编辑 */
async function handleSubmit() {
  if (!addFormRef.value) return
  await addFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning("请完善表单信息")
      return
    }
    try {
      if (isEdit.value) {
        await updateCardDataApi(addForm)
      } else {
        await createCardDataApi(addForm)
      }
      ElMessage.success("保存成功")
      dialog.visible = false
      addFormRef.value?.resetFields()
      await handleSearch()
    } catch {
      ElMessage.error("保存失败")
    }
  })
}

/* 取消添加/编辑 */
function handleCancel() {
  dialog.visible = false
  addFormRef.value?.resetFields()
}

/* 删除 */
async function handleDelete(row: CardItem) {
  try {
    await ElMessageBox.confirm(`确认删除 ${row.id} ？`, "提示")
    const { data } = await deleteCardDataApi(String(row.id))
    ElMessage.success(data || "删除成功")
    await handleSearch()
  } catch (err) {
    if (err !== "cancel") ElMessage.error("删除失败")
  }
}

/* 批量删除 */
async function handleBatchDel() {
  if (!selectedRows.value.length) return ElMessage.warning("请先勾选数据")
  try {
    await ElMessageBox.confirm("确认批量删除？", "提示")
    const ids = selectedRows.value.map(r => r.id).join(",")
    const res = await deleteCardDataApi(ids)
    ElMessage.success(res.data || "删除成功")
    selectedRows.value = []
    await handleSearch()
  } catch (err) {
    if (err !== "cancel") ElMessage.error("删除失败")
  }
}

/* 续费弹窗 */
interface RenewForm {
  cardStartDate: string
  cardEndDate: string
  paymentAmount: string
  paymentMethod: "Alipay" | "WeChat" | "Cash"
  carInfoId: number
}

const renewDialog = reactive({ visible: false, title: "月卡续费" })
const renewFormRef = ref<FormInstance>()
const renewForm = reactive<RenewForm>({
  cardStartDate: "",
  cardEndDate: "",
  paymentAmount: "",
  paymentMethod: "Alipay",
  carInfoId: 0
})
const paymentOpts = [
  { label: "支付宝", value: "Alipay" },
  { label: "微信", value: "WeChat" },
  { label: "线下", value: "Cash" }
]
const renewRules = reactive<FormRules<RenewForm>>({
  cardStartDate: [{ required: true, message: "请选择起始有效时间", trigger: "change" }],
  cardEndDate: [{ required: true, message: "请选择截止有效时间", trigger: "change" }],
  paymentAmount: [{ required: true, message: "请输入支付金额", trigger: "blur" }],
  paymentMethod: [{ required: true, message: "请选择支付方式", trigger: "change" }]
})

function handleOpenRenew(row: CardItem) {
  renewForm.carInfoId = row.id
  renewDialog.visible = true
  Object.assign(renewForm, {
    cardStartDate: "",
    cardEndDate: "",
    paymentAmount: "",
    paymentMethod: "Alipay"
  })
}

function handleCancelRenew() {
  renewDialog.visible = false
  renewFormRef.value?.resetFields()
}

async function handleSubmitRenew() {
  if (!renewFormRef.value) return
  // 把校验包在 Promise 里
  const valid = await new Promise<boolean>(resolve =>
    renewFormRef.value!.validate(resolve)
  )
  if (!valid) return ElMessage.warning("请完善表单信息")
  try {
    await renewCardDataApi(renewForm)
    ElMessage.success("续费成功")
    renewDialog.visible = false
    renewFormRef.value?.resetFields()
    await handleSearch()
  } catch {
    ElMessage.error("续费失败")
  }
}
/* 查看 */
async function handleView(row: CardItem) {
  const res = await getMonthCardDetailDataApi(row.id)
  // 使用类型断言确保 res 的类型安全
  const message = typeof res.data === "string" ? res.data : JSON.stringify(res.data, null, 2)
  ElMessageBox.confirm(message, "车辆详情", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "info",
    customClass: "my-messagebox",
    center: true,
    closeOnClickModal: false
  })
}

/* 表格多选 */
function handleSelectionChange(rows: CardItem[]) {
  selectedRows.value = rows
}

/* 初始化 */
handleSearch()
</script>

<template>
  <div class="card-container">
    <!-- 搜索 -->
    <div class="search-container flex items-center gap-4 pb-4 border-b border-gray-200">
      <div class="flex items-center gap-2">
        <span class="search-label text-sm text-gray-600">车牌号码：</span>
        <el-input v-model="searchForm.carNumber" clearable placeholder="请输入车牌号码" class="w-48" />
      </div>
      <div class="flex items-center gap-2">
        <span class="search-label text-sm text-gray-600">车主姓名：</span>
        <el-input v-model="searchForm.personName" clearable placeholder="请输入车主姓名" class="w-48" />
      </div>
      <div class="flex items-center gap-2">
        <span class="search-label text-sm text-gray-600">状态：</span>
        <el-select v-model="searchForm.cardStatus" clearable class="w-48">
          <el-option v-for="item in statusOpts" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <el-button type="primary" @click="handleSearch" class="ml-4">
        查询
      </el-button>
    </div>

    <!-- 操作按钮 -->
    <div class="create-container">
      <el-button type="primary" @click="handleAdd">
        添加月卡
      </el-button>
      <el-button @click="handleBatchDel">
        批量删除
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" />
      <el-table-column prop="personName" label="车主名称" />
      <el-table-column prop="phoneNumber" label="联系方式" />
      <el-table-column prop="carNumber" label="车牌号码" />
      <el-table-column prop="carBrand" label="车辆品牌" />
      <el-table-column prop="totalEffectiveDate" label="剩余有效天数" />
      <el-table-column label="状态">
        <template #default="{ row }">
          <span>
            {{ row.cardStatus === 0 ? '正常' : '已过期' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="220">
        <template #default="{ row }">
          <el-button size="small" type="text" @click="handleOpenRenew(row)">
            续费
          </el-button>
          <el-button size="small" type="text" @click="handleView(row)">
            查看
          </el-button>
          <el-button size="small" type="text" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button size="small" type="text" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="page-container">
      <el-pagination
        v-model:current-page="page.page"
        v-model:page-size="page.pageSize"
        :total="page.total"
        layout="total, prev, pager, next"
        @current-change="handleSearch"
      />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="580px">
      <div class="form-container">
        <el-form label-width="100px" :model="addForm" ref="addFormRef" :rules="rules">
          <el-form-item label="车主姓名" prop="personName">
            <el-input v-model="addForm.personName" />
          </el-form-item>
          <el-form-item label="联系方式" prop="phoneNumber">
            <el-input v-model="addForm.phoneNumber" />
          </el-form-item>
          <el-form-item label="车牌号码" prop="carNumber">
            <el-input v-model="addForm.carNumber" />
          </el-form-item>
          <el-form-item label="车辆品牌" prop="carBrand">
            <el-input v-model="addForm.carBrand" />
          </el-form-item>
          <el-form-item label="有效时间开始" prop="cardStartDate">
            <el-date-picker v-model="addForm.cardStartDate" type="date" placeholder="选择开始日期" style="width:100%" />
          </el-form-item>
          <el-form-item label="有效时间结束" prop="cardEndDate">
            <el-date-picker v-model="addForm.cardEndDate" type="date" placeholder="选择结束日期" style="width:100%" />
          </el-form-item>
          <el-form-item label="支付金额" prop="paymentAmount">
            <el-input v-model="addForm.paymentAmount" />
          </el-form-item>
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="addForm.paymentMethod" placeholder="请选择支付方式">
              <el-option label="支付宝" value="Alipay" />
              <el-option label="微信" value="WeChat" />
              <el-option label="线下" value="Cash" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="small" @click="handleCancel">
          取消
        </el-button>
        <el-button size="small" type="primary" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 续费弹窗 -->
    <el-dialog v-model="renewDialog.visible" :title="renewDialog.title" width="500px">
      <el-form label-width="120px" :model="renewForm" ref="renewFormRef" :rules="renewRules">
        <el-form-item label="起始有效时间" prop="cardStartDate">
          <el-date-picker v-model="renewForm.cardStartDate" type="date" placeholder="选择开始日期" style="width:100%" />
        </el-form-item>
        <el-form-item label="截止有效时间" prop="cardEndDate">
          <el-date-picker v-model="renewForm.cardEndDate" type="date" placeholder="选择结束日期" style="width:100%" />
        </el-form-item>
        <el-form-item label="支付金额" prop="paymentAmount">
          <el-input v-model="renewForm.paymentAmount" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="renewForm.paymentMethod" placeholder="请选择支付方式">
            <el-option v-for="item in paymentOpts" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" @click="handleCancelRenew">
          取消
        </el-button>
        <el-button size="small" type="primary" @click="handleSubmitRenew">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.card-container {
  @apply p-5 bg-white;
}
.search-container {
  @apply flex items-center border-b border-gray-100 pb-5;
}
.create-container {
  @apply my-2;
}
.page-container {
  @apply py-1 text-right;
}
.form-container {
  @apply px-20;
}
.my-messagebox {
  border-radius: 8px;
  .el-message-box__header {
    background-color: #f0f2f5;
    color: #303133;
    font-weight: 500;
  }
  .el-message-box__title {
    font-size: 16px;
  }
  .el-message-box__content {
    font-size: 14px;
    color: #606266;
    line-height: 1.5;
  }
  .el-button--primary {
    background-color: #409eff;
    border-color: #409eff;
    border-radius: 4px;
  }
  .el-button--default {
    border-radius: 4px;
  }
}
</style>
